import {
  _decorator,
  CCInteger,
  Component,
  Node,
  instantiate,
  Prefab,
  Vec3,
  math,
  Input,
  input,
  AudioClip,
} from 'cc'
import { GameManager } from './GameManager'
import { Enemy } from './Enemy'
import { AudioMgr } from './AudioMgr'
const { ccclass, property } = _decorator

@ccclass('EnemyManager')
export class EnemyManager extends Component {
  // 小飞机
  @property({ type: Prefab })
  enemy0Prefab: Prefab = null
  @property({ type: CCInteger })
  enemy0SpawnRate: number = 1

  // 中飞机
  @property({ type: Prefab })
  enemy1Prefab: Prefab = null
  @property({ type: CCInteger })
  enemy1SpawnRate: number = 4

  // 大飞机
  @property({ type: Prefab })
  enemy2Prefab: Prefab = null
  @property({ type: CCInteger })
  enemy2SpawnRate: number = 8

  // bomb使用音效
  @property({ type: AudioClip })
  useBombSound: AudioClip = null

  // 上次点击时间
  lastClickTime: number = 0
  // 双击阈值
  doubleClickInterval: number = 0.3
  protected onLoad(): void {
    this.lastClickTime = 0
    input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
  }
  onTouchEnd() {
    let currentTime = Date.now()
    let timeDiff = (currentTime - this.lastClickTime) / 1000
    if (timeDiff < this.doubleClickInterval) {
      // 双击
      this.onDoubleClick()
    }
    this.lastClickTime = currentTime
  }
  onDoubleClick() {
    const gameManager = GameManager.getInstance()
    if (gameManager.bombCount > 0) {
      AudioMgr.inst.playOneShot(this.useBombSound, 1)
      gameManager.minusBomb()
      for (const enemy of this.node.children) {
        // 将所有enemy的hp设置为0
        enemy.getComponent(Enemy).enemyDead()
      }
    }
  }

  start() {
    this.schedule(this.enemy0Spawn, this.enemy0SpawnRate)
    this.schedule(this.enemy1Spawn, this.enemy1SpawnRate)
    this.schedule(this.enemy2Spawn, this.enemy2SpawnRate)
  }

  protected onDestroy(): void {
    this.unscheduleAllCallbacks()
    // this.unschedule(this.enemy0Spawn)
    // this.unschedule(this.enemy1Spawn)
    // this.unschedule(this.enemy2Spawn)
    input.off(Input.EventType.TOUCH_MOVE, this.onTouchEnd, this)
  }

  enemy0Spawn() {
    this.enemySpawn(this.enemy0Prefab, -200, 200, 455)
  }
  enemy1Spawn() {
    this.enemySpawn(this.enemy1Prefab, -200, 200, 455)
  }
  enemy2Spawn() {
    this.enemySpawn(this.enemy2Prefab, -155, 155, 550)
  }
  enemySpawn(enemyPrefab: Prefab, minX: number, maxX: number, Y: number) {
    const enemy = instantiate(enemyPrefab)
    this.node.addChild(enemy)
    enemy.setPosition(new Vec3(math.randomRangeInt(minX, maxX), Y, 0))
  }
}
